/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.gpicalculator.servlet;

import it.polimi.games.epkb.controller.GpiKpiJpaController;
import it.polimi.games.epkb.controller.ObservedComponentJpaController;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.gpicalculator.GpiCalculator;
import it.polimi.games.gpicalculator.GpiCalculatorDaemon;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author plebani
 */
public class GPICalculatorServlet extends HttpServlet {

    String mFilePath;
    String octavePath;
    long daemonDuration;
    long gpiKpiRefreshPeriod;
    GpiCalculatorDaemon daemon;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);


        Logger.getLogger(GPICalculatorServlet.class.getName()).log(Level.INFO, "Gpi Calculator started");

        mFilePath = this.getInitParameter("mfilesdir"); // path of m-file with Gpi/Kpi definition

        mFilePath = config.getServletContext().getRealPath("/") + mFilePath;

        Logger.getLogger(GPICalculatorServlet.class.getName()).log(Level.INFO, "mFilePath = " + mFilePath);


        octavePath = this.getInitParameter("octavedir"); // Octave executable path

        Logger.getLogger(GPICalculatorServlet.class.getName()).log(Level.INFO, "octavePath = " + octavePath);

        daemonDuration = 0; // duration of simulation in seconds
        gpiKpiRefreshPeriod = Long.parseLong(this.getInitParameter("refresh")); // time period between two Gpi/Kpi refreshes in seconds

        Logger.getLogger(GPICalculatorServlet.class.getName()).log(Level.INFO, "refresh = " + gpiKpiRefreshPeriod);
        daemon = new GpiCalculatorDaemon(mFilePath, octavePath, daemonDuration, gpiKpiRefreshPeriod);

        // so it starts automatically when deployed
        daemon.run();
        //this.start(config);

    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {


            if (daemon != null && daemon.isRunning()) {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet GPICalculatorServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>GPI Calculator is already running</h1>");
                out.println("</body>");
                out.println("</html>");
            } else {
                daemon.run();
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet GPICalculatorServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>GPI Calculator started</h1>");
                out.println("</body>");
                out.println("</html>");
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void destroy() {
        this.daemon.done();
    }

  
}